package com.hgyc.mom.tool.util;

import com.hgyc.mom.common.constant.Constants;
import com.hgyc.mom.common.constant.ScheduleConstants;
import com.hgyc.mom.common.spring.SpringUtils;
import com.hgyc.mom.common.util.ExceptionUtils;
import com.hgyc.mom.common.util.StringUtils;
import com.hgyc.mom.common.util.bean.BeanUtils;
import com.hgyc.mom.tool.entity.JobLog;
import com.hgyc.mom.tool.service.JobLogService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 抽象quartz调用
 *
 * @author fwj
 */
public abstract class AbstractQuartzJob implements Job {
    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static ThreadLocal<LocalDateTime> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        com.hgyc.mom.tool.entity.Job toolJob = new com.hgyc.mom.tool.entity.Job();
        BeanUtils.copyBeanProp(toolJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));
        try {
            before(context, toolJob);
            if (toolJob != null) {
                doExecute(context, toolJob);
            }
            after(context, toolJob, null);
        } catch (Exception e) {
            log.error("任务执行异常  - ：", e);
            after(context, toolJob, e);
        }
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param toolJob 系统计划任务
     */
    protected void before(JobExecutionContext context, com.hgyc.mom.tool.entity.Job toolJob) {
        threadLocal.set(LocalDateTime.now());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param toolJob 系统计划任务
     */
    protected void after(JobExecutionContext context, com.hgyc.mom.tool.entity.Job toolJob, Exception e) {
        LocalDateTime startTime = threadLocal.get();
        threadLocal.remove();

        final JobLog jobLog = new JobLog();
        jobLog.setJobName(toolJob.getJobName());
        jobLog.setJobGroup(toolJob.getJobGroup());
        jobLog.setInvokeTarget(toolJob.getInvokeTarget());
        jobLog.setStartTime(startTime);
        jobLog.setStopTime(LocalDateTime.now());
        // 计算持续时间
        Duration duration = Duration.between(startTime, jobLog.getStopTime());
        long runMs = duration.toMillis();
        jobLog.setJobMessage(jobLog.getJobName() + " 总共耗时：" + runMs + "毫秒");
        if (e != null) {
            jobLog.setStatus(Constants.FAIL);
            String errorMsg = StringUtils.substring(ExceptionUtils.getExceptionMessage(e), 0, 2000);
            jobLog.setExceptionInfo(errorMsg);
        } else {
            jobLog.setStatus(Constants.SUCCESS);
        }

        // 写入数据库当中
        SpringUtils.getBean(JobLogService.class).save(jobLog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param job     系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, com.hgyc.mom.tool.entity.Job job) throws Exception;
}
